Windows Mobile – tasker2 runs and stops applications periodically

Tasker2 is a tool to launch or kill applications periodically using windows mobile scheduler. It was born to control the running of agent software on windows mobile at specified times. The problem with the agent software was that it does not open/close connections only on usage times but all the time and the device’s battery was drain very fast. We decided to write a helper that would launch and kill the agent to have it running only within a defined time frame.

Background process

We could have written a background process to run external tasks periodically. But the main disadvantage of timers and threads in background processes is that they do not run, if the device is in suspend mode.
To ensure that tasks will be launched also if the device is sleeping, we decided to use the windows mobile scheduler. There are functions inside the notification API to create notifications that will run an application at a specified time. This is what we call a schedule.

The scheduler (notification API)

After a timed schedule has been done by the scheduler, the schedule is removed from the notification database. If you like to have a periodic schedule, you have to ensure that a new schedule is created inside your code.

Pitfalls

During development we found many pitfalls in conjunction with the windows mobile scheduler. This is why I decided to write this post.

The tasks

Tasker2 is a console application without any GUI but it will write a log with all you need to know. Tasker2 supports up to ten tasks. A task is defined using the registry. Every task has an entry for start and stop times, the application to control, an interval for the schedule and a flag for control if a task is only to be run on external power:

REGEDIT4

[HKLM\Software\Tasker\Task1]
"active":DWORD=1
"exe":="\Windows\fexplore.exe"
"arg":="\My Documents"
"start":="1423"
"stop":="1523"
"interval":="2400"
"startOnAConly":DWORD=0;

active: if active is 0, tasker2 will not kill or start the process
exe: name of the process executable to start or kill
arg: arguments to be when launching the executable
start: when to start the executable the next time
stop: when to kill the process the next time
interval: when a start or kill has been executed, tasker2 will create a new schedule using this interval. If the interval is “0010”, the start process will be scheduled for every 10 minutes.
startOnAConly: if 1 and when a process has to be started, the process will only be started if the device is on external power

The scheduler

First, tasker2 is normally only launched one time manually and all future calls are made by the scheduler. Tasker2 will clear and schedule all planned tasks as defined in the registry if it is launched without arguments.

The scheduler is a task manager running all the time in windows mobile. If a timed schedule is reached, the scheduler will launch the specified application, see also here . This will also work if the device is in suspend mode (sleeps). The scheduler can also fire on special events like time or hardware changes (ON_RS232_CONNECT for example). See also my post here [http://www.hjgode.de/wp/2010/03/06/irunatevent/].

Theory of operation

Tasker2 uses command line arguments to control itself. The scheduler launches tasker2 with the specified arguments and tasker2 will then run or kill the defined task.

Delayed schedules (pitfall 1)

If your device supports a real power down, the scheduler will not awake the device and is not able to launch the defined schedules. When the device is later powered on, it will schedule all past schedules at once. This is what we call a ‘delayed schedule’ and a flooding of launches. Flooding in the mean of many schedules of tasker2 occurring at the same time for past tasks.
To avoid concurrent changes to the registry and scheduler entries, tasker2 uses a mutex to ensure only one instance is continuing execution. Subsequent instances will wait for existing instances before they do there work.

	//##################### dont run if already running #############################
	nclog(L"Checking for Mutex (single instance allowed only)...\n");

	hMutex=CreateMutex(NULL, TRUE, MY_MUTEX);
	if(hMutex==NULL){
		//this should never happen
		nclog(L"Error in CreateMutex! GetLastError()=%i\n", GetLastError());
		nclog(L"-------- END -------\n");
		return -99;
	}
	DWORD dwLast = GetLastError();
	if(dwLast== ERROR_ALREADY_EXISTS){//mutex already exists, wait for mutex release
		nclog(L"\tAttached to existing mutex\n");
		nclog(L"................ Waiting for mutex release......\n");
		WaitForSingleObject( hMutex, INFINITE );
		nclog(L"++++++++++++++++ Mutex released. +++++++++++++++\n");
	}
	else{
		nclog(L"\tCreated new mutex\n");
	}

	//##################### dont run if already running #############################

On a delayed, flooding schedule ALL pending tasks are scheduled and possibly a Time_Changed string is sent to the pending tasks. This flooding will be serialized as tasker2 waits for existing tasker2 instances.

Time and time zone changes (pitfall 2)

When the time is changed on the device, the scheduler will inform all timed tasks. Tasker2 must then recalculate new schedules based on current local time. The scheduler launches the defined applications with the TIME_CHANGED string as argument.

		
                 else if(wcsicmp(argv[1], APP_RUN_AFTER_TIME_CHANGE)==0 || wcsicmp(argv[1], APP_RUN_AFTER_TZ_CHANGE)==0){
			nclog(L"got '%s' signaled\n", argv[1]);
				//better to reread the current time we work with, possibly we have been blocked
				g_tmCurrentStartTime=getLocalTime(&g_tmCurrentStartTime);
				//now again check if we have a valid date
				nclog(L"Checking for valid date/time...\n");
				if( ((g_tmCurrentStartTime.tm_year+1900)*100 + g_tmCurrentStartTime.tm_mon+1) < 201111){
					nclog(L"scheduling event notifications\n");
					//clear and renew all event notifications
					#ifndef TESTMODE
						RunAppAtTimeChangeEvents(szTaskerEXE);
					#endif
					nclog(L"Date/Time not valid!\n*********** END ************\n");
					return 0xBADCAB1E;
				}
				nclog(L"Date/Time after 11 2011. OK\n");

			//schedule all active tasks
			int iCount = scheduleAllTasks();
			nclog(L"Scheduled %i Tasks\n", iCount);
		}

Additionally we found that the time changes may also occur during program launch or as tasker2 instances wait for another tasker2 instance. So tasker2 uses only one (in real two) calls to get the current time. This is essential, as tasker2 uses the current time to re-schedule tasks. The current time is called at the beginning, before tasker2 waits for the mutex. This is the time tasker2 was launched. If there has been a time_changed schedule, tasker2 will use another call to the current time, as it may have changed between the launch and the further execution of the code – after the mutex is released and the current instance is allowed to run.

Delayed schedules II (pitfall 3)

As only one instance of tasker2 is executing, it may happen, that the current time and the task time do not match exactly. Although the scheduler may do its best to launch tasker2 at the right time, the execution may be delayed in regards of the time the task is to be scheduled and the current time. This is another delayed schedule compared to the above flooding of schedules after a power down/up cycle.
It may also happen that a lot of tasker2 instances are waiting for execution, you know that we can have up to ten tasks. This may also lead to ‘delayed’ code execution, but should be in a small time frame of some minutes only.
Therefor tasker2 supports a maximum allowed delay time to distinguish between allowed and flooding delayed calls.

		//is this a delayed schedule?
		nclog(L"\tchecking for delayed schedule...\n");
		int iDeltaMinutes;
		__time64_t ttStart;
		__time64_t ttStop;
		__time64_t ttCurr;
		ttStop = _mktime64(&(_Tasks[iTask].stStopTime));
		ttStart = _mktime64(&(_Tasks[iTask].stStartTime));
		ttCurr = _mktime64(&g_tmCurrentStartTime);

		if(thisTaskType==stopTask){
			//difftime(timer1, timer0) returns the elapsed time in seconds, from timer0 to timer1
			iDeltaMinutes = difftime(ttCurr, ttStop)/60;// stDeltaMinutes(_Tasks[iTask].stStopTime, g_CurrentStartTime);
			nclog(L"stStopTime = '%s', ", getLongStrFromTM(_Tasks[iTask].stStopTime));
		}
		else{
			iDeltaMinutes = difftime(ttStart, ttCurr)/60;// stDeltaMinutes(_Tasks[iTask].stStartTime, g_CurrentStartTime);
			nclog(L"stStartTime = '%s', ", getLongStrFromTM(_Tasks[iTask].stStartTime));
		}

Adding a schedule

I am using central functions in code to add or remove schedules. Here is a sample of how a schedule is added:

...
#include "notify.h"
...
//--------------------------------------------------------------------
// Function name  : ScheduleRunApp
// Description    : add a schedule for exe with args at the time
// Argument       : LPCTSTR szExeName
// Argument       : LPCTSTR szArgs
// Argument       : struct tm tmTime
// Return type    : HRESULT, 0 for no error
//--------------------------------------------------------------------
HRESULT ScheduleRunApp(LPCTSTR szExeName, LPCTSTR szArgs, struct tm tmTime)
{
	HRESULT hr = S_OK;
	HANDLE hNotify = NULL;

	// set a CE_NOTIFICATION_TRIGGER
	CE_NOTIFICATION_TRIGGER notifTrigger;
	memset(&notifTrigger, 0, sizeof(CE_NOTIFICATION_TRIGGER));
	notifTrigger.dwSize = sizeof(CE_NOTIFICATION_TRIGGER);

	// calculate time
	SYSTEMTIME st = {0};
	//GetLocalTime(&st); //v.2.28

	st = convertTM2SYSTEMTIME(&st, &tmTime); //use provided new datetime

	wsprintf(str, L"Next run at: %02i.%02i.%02i %02i:%02i:%02i",
										st.wDay, st.wMonth , st.wYear,
										st.wHour , st.wMinute , st.wSecond );
	nclog(L"\tScheduleRunApp: %s\n", str);

	notifTrigger.dwType = CNT_TIME;
	notifTrigger.stStartTime = st;

	// timer: execute an exe at specified time
	notifTrigger.lpszApplication = (LPTSTR)szExeName;
	notifTrigger.lpszArguments = (LPTSTR)szArgs;

	hNotify = CeSetUserNotificationEx(0, &notifTrigger, NULL);
	// NULL because we do not care the action
	if (!hNotify) {
		hr = E_FAIL;
		nclog(L"\tScheduleRunApp: CeSetUserNotificationEx FAILED...\n");
	} else {
		// close the handle as we do not need to use it further
		CloseHandle(hNotify);
		nclog(L"\tScheduleRunApp: CeSetUserNotificationEx succeeded...\n");
	}
	return hr;
}

The main code

The main function is processStartStopCmd() beside createNextSchedule(). It does all the scheduling and time calculations.

/*	########################################################
		Process -s and -k comd line args
	########################################################
*/
//--------------------------------------------------------------------
// Function name  : processStartStopCmd
// Description    : calc new start/stop time, add schedules and start/kill application
// Argument       : TCHAR* argv[], the cmdLine array
// Return type    : int, 0 for no error
//--------------------------------------------------------------------
int processStartStopCmd(TCHAR* argv[]){
	int iReturn = 0;

	BOOL bIsDelayedSchedule = TRUE; //used to save a delayed schedule situation

	enum taskType{
		startTask = 1,
		stopTask = 2
	};
	taskType thisTaskType;

	if(wcsicmp(argv[1], L"-k")==0)	//kill taskX app
		thisTaskType=stopTask;
	else
		thisTaskType=startTask;

	int iTask = getTaskNumber(argv[2]);
	if(_Tasks[iTask].iActive==1){
		//create a new schedule cmd line for tasker
		TCHAR strTaskCmdLine[MAX_PATH];

		if(thisTaskType==stopTask)
			wsprintf(strTaskCmdLine, L"-k task%i", iTask+1); //the cmdLine for tasker.exe for this task
		else
			wsprintf(strTaskCmdLine, L"-s task%i", iTask+1); //the cmdLine for tasker.exe for this task	

		//clear all tasker schedules for taskX
		nclog(L"Clearing all schedules for Task%i with '%s'\n", iTask+1, strTaskCmdLine);
		notiClearRunApp(szTaskerEXE, strTaskCmdLine);

		struct tm tmNewTime = {0};
		short shHour	=	_Tasks[iTask].stDiffTime.tm_hour;
		short shMin		=	_Tasks[iTask].stDiffTime.tm_min;
		short shDays	=	0;
		if(shHour>=24){	//hour interval value is one day or more
			shDays = (short) (shHour / 24);
			shHour = (short) (shHour % 24);
		}				

		//is this a delayed schedule?
		nclog(L"\tchecking for delayed schedule...\n");
		int iDeltaMinutes;
		__time64_t ttStart;
		__time64_t ttStop;
		__time64_t ttCurr;
		ttStop = _mktime64(&(_Tasks[iTask].stStopTime));
		ttStart = _mktime64(&(_Tasks[iTask].stStartTime));
		ttCurr = _mktime64(&g_tmCurrentStartTime);

		if(thisTaskType==stopTask){
			//difftime(timer1, timer0) returns the elapsed time in seconds, from timer0 to timer1
			iDeltaMinutes = difftime(ttCurr, ttStop)/60;// stDeltaMinutes(_Tasks[iTask].stStopTime, g_CurrentStartTime);
			nclog(L"stStopTime = '%s', ", getLongStrFromTM(_Tasks[iTask].stStopTime));
		}
		else{
			iDeltaMinutes = difftime(ttStart, ttCurr)/60;// stDeltaMinutes(_Tasks[iTask].stStartTime, g_CurrentStartTime);
			nclog(L"stStartTime = '%s', ", getLongStrFromTM(_Tasks[iTask].stStartTime));
		}

		nclog(L"current time = '%s'\n", getLongStrFromTM(g_tmCurrentStartTime));
		nclog(L"interval is: %id%02ih%02im\n", shDays, shHour, shMin);
		nclog(L"\tdelta is %i minutes\n", iDeltaMinutes);

		//started BEFORE scheduled time, iDelta is negative
		if(iDeltaMinutes<0){
			if(thisTaskType==stopTask){
				//calculate new schedules or leave them as is?
				//tmNewTime=_Tasks[iTask].stStopTime;	//leave them as is
				tmNewTime=createNextSchedule(_Tasks[iTask].stStopTime, shDays,shHour,shMin); //calc new schedule
			}
			else{
				//tmNewTime=_Tasks[iTask].stStartTime;	//leave them as is
				tmNewTime=createNextSchedule(_Tasks[iTask].stStartTime, shDays,shHour,shMin); //calc new schedule
			}
#ifndef TESTMODE
			ScheduleRunApp(szTaskerEXE, strTaskCmdLine, tmNewTime);
#endif
			nclog(L"*** re-scheduled future task *** \n");
			return 0;
		}

		int iMaxDelay = getMaxDelay();
		nclog(L"\tmax allowed diff for delayed schedule recognition is plus %i\n", iMaxDelay);

		if( iDeltaMinutes > iMaxDelay ) //is the time diff greater than 1 minute
		{
			bIsDelayedSchedule = TRUE;
			nclog(L"*** delayed schedule *** recognized\n");
			//this is a delayed schedule
			DOUBLE dbTimeDiff = 0;

			//it may happen that the schedule is far in the future
			//we calc the next schedule on base of the current time by using the saved start/stop time
			//is just greater than the current time
			if(thisTaskType==stopTask)
				tmNewTime=_Tasks[iTask].stStopTime;
			else
				tmNewTime=_Tasks[iTask].stStartTime;

			tmNewTime = createNextSchedule(tmNewTime, shDays, shHour, shMin);
		}
		else{
			nclog(L"*** NO delayed schedule *** recognized\n");
			if(thisTaskType==stopTask){
				tmNewTime = createNextSchedule(_Tasks[iTask].stStopTime, shDays, shHour, shMin);
			}
			else{
				tmNewTime = createNextSchedule(_Tasks[iTask].stStartTime, shDays, shHour, shMin);
			}
			bIsDelayedSchedule=FALSE;
		}

		//create a new kill or start schedule with new time
		nclog(L"Creating new schedule for '%s' in Task%i\n", _Tasks[iTask].szExeName, iTask+1);
#ifndef TESTMODE
		ScheduleRunApp(szTaskerEXE, strTaskCmdLine, tmNewTime);
#endif
		//save new changed stop/start ime
		if(thisTaskType==stopTask)
			regSetStopTime(iTask, tmNewTime);
		else
			regSetStartTime(iTask, tmNewTime);

		if(!bIsDelayedSchedule){
			nclog(L"Not a delayed schedule\n");
			if(thisTaskType==startTask){
				if(_Tasks[iTask].bStartOnAConly){
					if(isACpowered()){
						nclog(L"Starting exe '%s' as on AC power\n", _Tasks[iTask].szExeName);
						runExe(_Tasks[iTask].szExeName, _Tasks[iTask].szArgs);
					}
					else{
						nclog(L"Skipping start of exe '%s' as not on AC power\n", _Tasks[iTask].szExeName);
					}
				}
				else{
					nclog(L"Starting exe '%s'\n", _Tasks[iTask].szExeName);
					runExe(_Tasks[iTask].szExeName, _Tasks[iTask].szArgs);
				}
			}
			else{ // a stop task
				//now kill the task's exe
				nclog(L"Killing exe '%s'\n", _Tasks[iTask].szExeName);
				DWORD iKillRes = killExe(_Tasks[iTask].szExeName);
				switch (iKillRes){
					case ERROR_NOT_FOUND:
						nclog(L"\texe not running\n");
						break;
					case 0:
						nclog(L"\texe killed\n");
						break;
					default:
						nclog(L"unable to kill exe. GetLastError=%08x\n", iKillRes);
						break;
				}
			}
		}
		else{
			nclog(L"Exec/Kill skipped as this is a delayed schedule\n");
		}
	}
	else
		nclog(L"\ttask %i is inactive (0x%02x)\n", iTask, _Tasks[iTask].iActive);

		return iReturn;
}

 Tasker2 control

Although you normally dont need to run tasker2 manually, I have added some command line arguments:

“-c”    instructs tasker2.exe to remove all tasker2 schedules of the scheduler database
“-r taskX”    deactivate processing of task with number X, sets the active flag to 0
“-a taskX”    activate processing of task number X, sets the active flag to 1
“-d”    dump a list of all active notifications of the windows mobile scheduler

Do not use -s taskX and -k taskX except for testing. The args ‘-s taskX’ and ‘-k taskX’ are only be used by the scheduler.

Log file

The log file will log all activities of tasker2 in the directory of tasker2.exe. It will grow until 1MB and then one log backup file is saved. So you may have two log files, one active and one backup of the previous log.

0xfacbcab2: ++++++++++++++++ Tasker v300 started +++++++++++++++++++
0xfacbcab2: Checking for Mutex (single instance allowed only)...
0xfacbcab2: 	Created new mutex
0xfacbcab2: ~~~ using actual localtime:
0xfacbcab2: 	 23.12.2011, 12:28
0xfacbcab2: CmdLine =
0xfacbcab2: Checking for valid date/time...
0xfacbcab2: Date/Time after 11 2011. OK
0xfacbcab2: Clearing Event Notifications...0xfacbcab2: OK
0xfacbcab2: ClearRunApp(): ...
0xfacbcab2: ClearRunApp(): CeClearUserNotification for handle: 0x3d00000f
0xfacbcab2: ClearRunApp(): CeClearUserNotification for handle: 0x33000025
0xfacbcab2: ClearRunApp(): CeClearUserNotification for handle: 0x3800002a
0xfacbcab2: ClearRunApp(): CeClearUserNotification for handle: 0x3b00001b
0xfacbcab2: ClearRunApp(): CeClearUserNotification for handle: 0x3800002e
0xfacbcab2: ClearRunApp(): CeClearUserNotification for handle: 0x3f00001e
0xfacbcab2: ClearRunApp(): CeClearUserNotification for handle: 0x37000016
0xfacbcab2: ClearRunApp(): CeClearUserNotification for handle: 0x3a000030
0xfacbcab2: ClearRunApp(): returns 8
0xfacbcab2: Cleared 8 Tasker schedules
0xfacbcab2: scheduleAllTasks: ClearAllSchedules for 8 tasks
0xfacbcab2: Clearing Event Notifications...0xfacbcab2: Clearing Event Notifications...0xfacbcab2: OK
0xfacbcab2: Adding Time_Change Event Notification...0xfacbcab2: OK
0xfacbcab2: Adding TZ_Change Event Notification...0xfacbcab2: OK
0xfacbcab2: Creating new Start Task schedule for '\Windows\notes.exe' in Task1
0xfacbcab2: 	calculating new schedule for '201112231300'...
0xfacbcab2: 	interval is: 0d01h00m
0xfacbcab2: 	schedule adjusted to '201112231300'
0xfacbcab2: 	ScheduleRunApp: Next run at: 23.12.2011 13:00:56
0xfacbcab2: 	ScheduleRunApp: CeSetUserNotificationEx succeeded...
0xfacbcab2: Creating new Kill Task schedule for '\Windows\notes.exe' in Task1
0xfacbcab2: 	calculating new schedule for '201112231300'...
0xfacbcab2: 	interval is: 0d01h00m
0xfacbcab2: 	schedule adjusted to '201112231300'
0xfacbcab2: 	ScheduleRunApp: Next run at: 23.12.2011 13:00:56
0xfacbcab2: 	ScheduleRunApp: CeSetUserNotificationEx succeeded...
...

The first entry in the log file is the current logging instance. As multiple instances may write randomly at the log, the instance number is needed to idetify which instance has written the current log line.

Changes

There are two variants of tasker2, one is using SYSTEMTIME and the other, new one uses time_t. I switched to time_t as it is more easy to do operations like add-one-day with time_t vars than with SYSTEMTIME.

The old variant (v234a) is available as a branch in the code repository: http://code.google.com/p/tasker2/source/browse/#svn%2Fbranch%2Fversion232%2FTasker

Tests

Fortunately I had great help by a tester of the software. Many thanks to Thomas B.

I built my only automatic test suite using batch files and a special build of tasker2.exe. If you uncomment the line //#define TESTMODE at the beginning of tasker2.cpp, the compiled app will be in test mode. That means it will not add or remove schedules to/from the windows mobile scheduler. There is another tool used in the test_run.bat that sets the date and time of the device remotely (ActiveSync or Windows Mobile Device Center connection).

The automatic test uses the great tools of itsutils and will set registry values, change date/time, launch tasker2, get the log and build a merged log with all essential data to check the function of tasker2:

http://code.google.com/p/tasker2/source/browse/#svn%2Ftrunk%2FTasker%2Ftest

Here is a snippet from the test_bat.bat:

@echo off

ECHO ############## START ###############
echo  MAKE SHURE THE RADIOS ARE OFF TO
echo  AVOID AUTOMATIC TIME SYNCS!
echo .
PAUSE Press any key to start

ECHO ############## START ############### >test_run.txt

echo Importing test reg keys...
echo Importing test reg keys... >>test_run.txt
pregutl @tasker2.reg >>test_run.txt

pdel \tasker2.exe.log.txt >NUL
pput -f ./tasker2.exe \tasker2.exe

ECHO TEST1...
ECHO 	set time manually to 01.01.2003 12:00
echo 	run tasker2.exe
ECHO ++++++++++++++ TEST1 ++++++++++++++++ >>test_run.txt
pregutl HKLM\Software\Tasker  >>test_run.txt
ECHO ------------------------------------- >>test_run.txt
ECHO set time manually to 01.01.2003 12:00 >>test_run.txt
ECHO ------------------------------------- >>test_run.txt
prun \SetDateTime.exe 200301011200
CALL :MYWAIT
prun \tasker2.exe
ECHO "############# Result:" >>test_run.txt
pregutl HKLM\Software\Tasker >>test_run.txt
ECHO *************** LOG  **************** >>test_run.txt
pget -f \tasker2.exe.log.txt
type tasker2.exe.log.txt >>test_run.txt
pdel \tasker2.exe.log.txt
ECHO ---------------TEST1  --------------- >>test_run.txt
ECHO .>>test_run.txt

Downloads

The full tasker2 source code is available at http://code.google.com/p/tasker2/source/browse

Tool to look at the scheduler database [NotificationList]: [Download not found]